from codec.Media import Media
from tkinter import *
from tkinter import ttk
import tkinter as ttk
import tkinter.filedialog
from json import load, dump
import codec
from os import system


root = Tk()
root.title('AutoEditting')
root.geometry('1920x1080')  #窗口的大小

mainframe = tkinter.Frame(root)
mainframe.grid(column=0, row=0)
filepath = StringVar()
exportPath = StringVar()


#
def get_by_menu():           #这个函数用来通过菜单栏中的Open来获取文件路径的功能
    filepath = tkinter.filedialog.askopenfilename(title=u'选择文件')
    #print(filepath)

def edit_vedio():            #这个函数用来开始剪辑并导出视频，目前只实现了选择输出文件夹并获取其路径的功能
    global out_path          #out_path为输出路径
    exportPath = tkinter.filedialog.askdirectory()
    #print(exportPath)

menubar = tkinter.Menu(root)
filemenu = tkinter.Menu(menubar,tearoff=0)
# 将上面定义的空菜单命名为File，放在菜单栏中，就是装入那个容器中
menubar.add_cascade(label='文件', font=('fangsongti',15),menu=filemenu,)

# 在File中加入New、Open、Save等小菜单，即我们平时看到的下拉菜单，每一个小菜单对应命令操作。
filemenu.add_command(label='导入视频',  font=('fangsongti',15),command=get_by_menu)
filemenu.add_command(label='导出视频',  font=('fangsongti',15),command=edit_vedio)
filemenu.add_command(label='退出',  font=('fangsongti',15),command=root.quit)  # 用tkinter里面自带的quit()函数

root.config(menu=menubar)
#


ttk.Label(mainframe, text='filepath', font=('fangsongti',25)).grid(column=1, row=1, sticky = W)
pathin = ttk.Entry(mainframe, text=filepath, textvariable=filepath, font=('fangsongti',25), width = 50).grid(column=2, row=1, sticky = W)
ttk.Button(mainframe, text='浏览', command = get_by_menu,font=('fangsongti',20), width = 8).grid(column=3, row=1, sticky = W)


ttk.Label(mainframe, text='export to', font=('fangsongti',25)).grid(column=1, row=2, sticky = W)
pathout = ttk.Entry(mainframe, textvariable=exportPath, font=('fangsongti',25), width = 50).grid(column=2, row=2, sticky = W)
ttk.Button(mainframe, text='浏览', command = edit_vedio,font=('fangsongti',20), width = 8).grid(column=3, row=2, sticky = W)

clipVars = []
ttk.Label(mainframe,font = ('fangsongti',25)).grid(column=1, row=3)  #只是一个用于布局的空行...没有实际作用


def preview(i):
    return lambda: system(f"ffplay -ss {clipVars[i]['start'].get()} -t {clipVars[i]['end'].get() - clipVars[i]['start'].get()} {filepath.get()}")


with open('./swap.json') as file:
    data = load(file)
    clipVars = [
        {
            'start': DoubleVar(value=x['start']),
            'end': DoubleVar(value=x['end'])
        }
        for x in sorted(codec.util.m2c(data['marks']), key=lambda x: x['start'])
    ]
#    for i in range(len(clipVars)):
#        ttk.Label(mainframe, text=f'Clip {i}').grid(column=1, row=i+3)
#        ttk.Entry(mainframe, textvariable=clipVars[i]['start']).grid(
#            column=2, row=i+3)
#        ttk.Entry(mainframe, textvariable=clipVars[i]['end']).grid(
#            column=3, row=i+3)
#        ttk.Button(mainframe, text='preview',
#                   command=preview(i)).grid(column=4, row=i+3)


    def hit_lb():
        values = lb.get(lb.curselection())
        lb_var.set(values)
#        s_beg.set( clipVars[values]['start'] )
#        s_end.set( clipVars[values]['end'] )
#        clipVars[values]['start'] = v_beg
#        clipVars[values]['end'] = v_end
        ttk.Label(mainframe, text=f'Clip {values}',font=('fangsongti',25), width = 15).grid(column=1, row=6)
        ttk.Entry(mainframe, textvariable=clipVars[values]['start'],font=('fangsongti',25), width = 15).grid(column=1, row=7)
        ttk.Entry(mainframe, textvariable=clipVars[values]['end'],font=('fangsongti',25), width = 15).grid(column=1, row=8)
        ttk.Button(mainframe, text='preview', command=preview(values),font=('fangsongti',25), width = 15).grid(column=1, row=9)
        print(values)




    values = 0
    lb_var = tkinter.IntVar()
    lb_select_var = tkinter.IntVar()
    len = len(clipVars)
    lb = tkinter.Listbox(mainframe, listvariable=lb_select_var, font=('Arial', 20),height = 16, width = 15) # 用于选择当前编辑的片段
    lb.grid(column = 1, row = 4)
    num = 1
    for i in range(1, len):
        lb.insert(tkinter.END, num)
        num = num + 1

    photo = PhotoImage(file="./VLOG.png")
    Label(mainframe, image=photo).grid(column=2, row=4)

    tkinter.Button(mainframe, text = '确定选择片段', command = hit_lb).grid(column = 1,row = 5)


    v_beg = StringVar()
    v_end = StringVar()

#    s_beg = tkinter.Scale(mainframe, label = "Begin Time",from_ = 0, to = 100, font=('Arial',18),orient=ttk.HORIZONTAL,
#            length=1100, showvalue=1, tickinterval=10, resolution=0.5, variable = v_beg)
#    s_beg.set(clipVars[values]['start'])
#    s_beg.grid(column = 2, row = 6)
#    s_end = tkinter.Scale(mainframe, label = "End Time",from_ = 0, to = 100, font=('Arial',18),orient=ttk.HORIZONTAL,
#            length=1100, showvalue=1, tickinterval=10, resolution=0.5, variable = v_end)
#    s_end.set(clipVars[values]['end'])
#    s_end.grid(column = 2, row = 7)



submit_frame = ttk.Frame(root)
submit_frame.grid(column=0, row=1)

def export():
    data = {
        'filepath': filepath.get(),
        'marks': []
    }
    for i in range(len(clipVars) - 1):
        data['marks'].append(
            {
                'label': 'bad',
                'start': clipVars[i]['start'].get(),
                'end': clipVars[i]['start'].get()
            }
        )
        data['marks'].append(
            {
                'label': 'good',
                'start': clipVars[i]['end'].get(),
                'end': clipVars[i]['end'].get()
            }
        )
    data['marks'].append(
        {
            'label': 'bad',
            'start': clipVars[-1]['start'].get(),
            'end': clipVars[-1]['start'].get()
        }
    )
    with open('./swap.json', 'w') as file:
        dump(data, file)
    media = Media()
    media.export(exportPath.get())


ttk.Button(submit_frame, text='export', command=export,font=('fangsongti',25), width = 15).grid(column=1, row=1)


def main():
    root.mainloop()
